<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\order\AppManage;
use app\admin\model\share\ShareUser;
use app\common\controller\Api;
use GuzzleHttp\Client;
use xingwu\Xingwu;
use app\admin\model\pay\Merchant;
use think\Db;
use addons\shopro\model\User as UserModel;

// use app\common\model\shoproOrder;
use addons\shopro\model\Order as shoproOrder;
use app\admin\model\share\CommonShare;
use app\admin\model\shopro\order\Split;
use app\admin\model\Recharge;


/**
 * 会员接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    // protected $noNeedLogin = ['pay'];
    protected $noNeedRight = '*';
    // public function _initialize()
    // {
    //     parent::_initialize();
    //     if (!Config::get('fastadmin.usercenter')) {
    //         $this->error(__('User center already closed'));
    //     }
    // }
    // 腾讯接口
    // https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=KUQBZ-FYDCU-YMVVN-2DDW5-7WDYE-5JBJR&ip=[IP地址]&callback=jQuery18301852690032249129_1600324416562&_=1600324417180
    // 携程
    // https://cdid.c-ctrip.com/model-poc2/h
    // ip.cn
    // https://www.ip.cn/api/index?ip=&type=0
    // dreamwq
    // https://api.dreamwq.com/api/getLocation
    /**
     * 微信支付先验证
     */
    public function wechatPay(){
        $fee = $this->request->post("fee");//充值金额
        $chage = Db::name("config")->where(['name'=>'is_chage'])->find();
        if($chage && $chage['value'] == 2){
            $this->error(__('钱包功能升级中,请使用提货券支付'), null, 2);
        }
        if ($fee) {
            if (!\think\Validate::is($fee, 'integer')) $this->error('亲，充值金额应为整数');

                $today9 = strtotime(date('Y-m-d ' . "9:00:00"));//9点
                $today21 = $today9 + 43200;//21点
                if ($today9 > time() || $today21 < time()) {
                   // $this->error(__('Pay time 9:00~21:00'));
                }
                if($fee>="10001"){
                    $this->error("充值金额最大值是10000元");
                }
                if($fee>="10001"){
                    $this->error("充值金额最大值是10000元");
                }
        }else{
            $this->error('金额必传', null, 2);
        }
        $this->success('验证通过');
    }
    function kdpay()
    {
        $url = Db::name("config")->where(['name' => 'url'])->find();
        if($url['value'] == 'https://ryt.bigchun.com'){
            $this->error('亲，支付宝正在升级中，请您使用微信支付', null, 2);
        }
        $type = $this->request->post("type")?:1;
        //my_debug(1,'$type--72');
        //my_debug(1,$type);
        if (empty($this->auth->id)) {
            $this->error('请登录后操作', null, 2);
        }

        //my_debug(1,'$this->auth-id-78');
        //my_debug(1,$this->auth->id);

        $fee = $this->request->post("fee");
        $openid = $this->request->post("openid");

        //my_debug(1,'$fee-87');
        //my_debug(1,$fee);


        $mchId = "KP10009718";
        $secretKey = "NWonqz4cp2OXH93OT9FYRGdpMYoFdNYi";
        $notify_url=url('api/pay/kdnotify', '', '', true);
        $ip = $_SERVER['REMOTE_ADDR'];
        $randsi = date("YmdHis") . rand(1000, 9999);

        $array=
            [
                "mch_id"=>$mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    "payment"=>'WXPAY',
                    "client_ip"=>$ip,
                    "out_trade_no"=>date("YmdHis") . rand(1000, 9999),
                    "fee"=>$fee * 100, //分
                    "body"=>"充值",
                    "notify_url"=>$notify_url,
                ],JSON_UNESCAPED_UNICODE),
            ];
	    //1微信 2支付宝
        $pay_type = 'wechat';
        if($type ==2){
            $pay_type = 'alipay';
            $array =
                [
                    "mch_id"=>$mchId,
                    "timestamp"=>time(),
                    "nonce_str"=>$randsi,
                    "sign_type"=>'MD5',
                    "content"=>json_encode([
                        "payment"=>'ALIPAY',
                        "client_ip"=>$ip,
                        "out_trade_no"=>date("YmdHis") . rand(1000, 9999),
                        "fee"=>$fee * 100, //分
                        "body"=>"充值",
                        "notify_url"=>$notify_url,
                    ],JSON_UNESCAPED_UNICODE),
                ];
        }
        foreach ($array as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $buff = "";
        ksort($Parameters);
        foreach ($Parameters as $k => $v) {
            $buff .= $k . "=" . $v . "&";
        }
        $String = '';
        if (strlen($buff) > 0) {
            $String = substr($buff, 0, strlen($buff) - 1);
        }
        $String = $String . "&secret_key=" . $secretKey;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $strings = strtoupper($String);
        $array['sign'] = $strings;
        file_put_contents('kk.txt',json_encode($array));
        $res = json_decode(self::http_post('https://pay.kudianvip.com/openapi/pay/kdh5pay',json_encode($array)), true);

        if($res['code'] != 0){
            $this->error('错误信息为：'.$res['msg']);
        }
        //返回参数格式设计
        if (!empty($res['result']))
        {
            $res_data=json_decode($res['result'],true);

            $in_data = [
                'order_sn'=>$res_data['pay_no'],
                'user_id'=>$this->auth->id,
                'transaction_id'=>$res_data['out_trade_no'],
                'total_fee'=>$res_data['fee']/100,
                'payment_json'=>$res['result'],
                'pay_type'=>$pay_type,
            ];
            // 获取IP
            $ip = $this->request->ip();
            $in_data['ip'] = $ip ?? '';
            (new Recharge())->save($in_data);

            $this->success('jsapi',$res_data);

        }else
        {
           // $this->AddLogAlert('调起支付错误','参数：'.json_encode($array).'|结果：'.json_encode($res));
            $this->error('错误信息为：'.$res['msg']);
        }
    }

    /**
     * [notify 回调充值]
     * @return [type]     [description]
     * @since  2022-09-27
     */
    public function parseParam($str)
    {
        $str  = stripslashes($str);

        $str = str_replace('&amp;','',$str);
        $str = str_replace('&quot;','',$str);
        $str = str_replace('quot;','',$str);
        $str = str_replace('{','',$str);
        $str = str_replace('}','',$str);
        $arr = explode(',',$str);
        $res = [];
        foreach ($arr as $k => $v) {
            $sub = explode(':',$v);
            $res[$sub[0]] = $sub[1];
        }
        return $res;

    }
    /**
     * [notify 回调充值]
     * @return [type]     [description]
     * @since  2022-09-27
     */
    public function kdnotify()
    {
        $post = $this->request->param();
        if($post['code'] == 0 ){
           $arr = $this->parseParam($post['result']);
            \think\Log::record(var_export($post, true), 'pay_notify');
            if($arr['status'] != 100){
                echo 'SUCCESS';
                $msg = '支付异常';
                return $msg;
            }

            // 获取订单
            $orders = Recharge::where('order_sn', '=', $arr['pay_no'])
                ->where('status', '=', 0)
                ->field(['id', 'order_sn', 'pay_fee', 'user_id', 'total_fee', 'xw_orderNo', 'xw_account', 'xw_code'])
                ->lock(true)
                ->find();

            // 处理订单
            if (!$orders) {
                \think\Log::record('error：' . '订单不存在或已充值', 'pay_notify');
                echo 'SUCCESS';
                $msg = '订单不存在或已充值';
                return $msg;
            }
            Db::startTrans();
            // 交易类型
            switch ('KD') {
                case 'PUR': //消费交易
                    # code...
                case 'KD'://酷点

                        $orders->status = 1;
                        $orders->pay_fee = $arr['fee']/100;
                        $orders->paytime = time();
                        $orders->mchId = $arr['mch_id'];
                    break;
                case 'VID': //撤销消费
                    # code...
                    // break;
                case 'SPC'://扫码支付撤销
                    # code...
                    // break;
                case 'RVK'://撤销（消费撤销、扫码撤销、预授权撤销、预授权完成撤销）
                    if ($post['respcode'] == '00') {
                        $orders->status = Recharge::STATUS_CANCEL;
                        // Merchant::where('id','=',$merchant['id'])->setInc('today_quota', $orders['total_fee']);
                        echo 'OK';
                    }
                    \think\Log::record('error：' . '订单撤销', 'pay_notify');
                    break;
                case 'PRE': //预授权
                    # code...
                    break;
                case 'CFM': //预授权完成
                    # code...
                    break;
                case 'RFD': //退货
                    # code...
                    break;
                case 'QRY': //查询
                    # code...
                    break;
                case 'SPQ'://扫码支付查询
                    # code...
                    break;
                default:
                    # code...
                    break;
            }
            \think\Log::record('trxtype交易类型：' . $arr['body'], 'pay_notify');
            \think\Log::record('respcode交易应答码：' . $arr['mch_id'], 'pay_notify');
            $orders->save();
            (new ShareUser)->userPriceLog($orders['user_id'], $orders['pay_fee'], 4,'订单号'.$arr['pay_no'].'充值成功',false,[]);
            Db::commit();

        }
        echo 'SUCCESS';

    }
    /**
     * 使用http_post提交
     * @param $url
     * @param $params
     * @param bool $contentType
     * @return bool|mixed|string
     */
    protected function http_post($url, $params, $contentType=true)
    {

        if (function_exists('curl_init')){
            // curl方式
            $oCurl = curl_init();
            if (stripos($url, 'https://') !== FALSE){
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            $string = $params;
            if (is_array($params)){
                $aPOST = array();
                foreach ($params as $key => $val) {
                    $aPOST[] = $key . '=' . urlencode($val);
                }
                $string = join('&', $aPOST);
            }
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, TRUE);
            //$contentType json处理
            if($contentType){
                $headers = array(
                    "Content-type: application/json;charset='utf-8'",
                );

                curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, $params);
            }else{
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, $string);
            }
            $response = curl_exec($oCurl);
            curl_close($oCurl);
            return $response;
        } elseif (function_exists('stream_context_create')) {
            // php5.3以上
            $opts = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => http_build_query($params),
                )
            );
            $_opts = stream_context_get_params(stream_context_get_default());
            $context = stream_context_create(array_merge_recursive($_opts['options'], $opts));
            return file_get_contents($url, false, $context);
        }else{
            return FALSE;
        }
    }
    /*public function pay(){
        $fee = $this->request->post("fee");
        $pay_data['fee'] = $fee*100;
        $pay_data['out_trade_no'] = date("YmdHis") . mt_rand(100000, 999999);
        $pay_data['body'] = "充值";
        $pay_data['client_ip'] = $_SERVER["REMOTE_ADDR"] ;

        $re_data['mch_id'] = 'KP10009718';
        $re_data['timestamp'] = time();
        $re_data['nonce_str'] = time()."dsffe";
        $re_data['sign_type'] = time()."MD5";
        $re_data['content'] = json_encode($pay_data);

    }*/
    //提交订单
    public function pay2()
    {


        $out_trade_no = $this->request->post("order_sn");
        $type = $this->request->post("type");
        $addevent = $this->request->post("addevent");
        $amount = $this->request->post("fee");
        $openid = $this->request->post("openid");

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }
        //  var_dump($amount);exit;
        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $info = get_addon_info('third');
        if (!$info || !$info['state']) {
            $this->error("请在后台安装第三方登录插件");
        }
        $params = [
            'amount' => $amount,
            'orderid'=> $out_trade_no,
            'type'=> 'wechat',
            'title'=> '余额充值',
            'notifyurl' => $notifyurl,
            'method'=> 'miniapp',
            'openid' => $openid,
        ];

       /* $payParams = \addons\epay\library\Service::submitOrder($params);
        var_dump($payParams);exit;*/
        ///
        try {
            //$response=Service::submitOrder($amount, $out_trade_no, 'wechat', "订单支付", $notifyurl, $returnurl,'miniapp',$openid);
            $response = Service::submitOrder($params);
            $in_data = [
                'order_sn'=>"cz".$out_trade_no,
                'user_id'=>$this->auth->id,
                'transaction_id'=>$out_trade_no,
                'total_fee'=>$amount,
                'payment_json'=>json_encode($params),
                'pay_type'=>$type,
            ];
            // 获取IP
            $ip = $this->request->ip();
            $in_data['ip'] = $ip ?? '';
            (new Recharge())->save($in_data);
        } catch (GatewayException $e) {
            throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
        }
        $response['out_trade_no'] = $out_trade_no;
        $this->success('请求成功',$response);

    }
    /**
     * [pay 支付]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function pay()
    {
        $order_sn = $this->request->post("order_sn");
        $type = $this->request->post("type");
        $addevent = $this->request->post("addevent");
        $fee = $this->request->post("fee");
        $chage = Db::name("config")->where(['name'=>'is_chage'])->find();
        if($chage && $chage['value'] == 2){
            $this->error(__('钱包功能升级中,请使用提货券支付'), null, 2);
        }
        if ($fee) {
            if (!\think\Validate::is($fee, 'integer')) $this->error('亲，充值金额应为整数', null, 2);

            if (config("project_name") != 'test') {
                $today9 = strtotime(date('Y-m-d ' . "9:00:00"));//9点
                $today21 = $today9 + 43200;//21点
                if ($today9 > time() || $today21 < time()) {
                   // $this->error(__('Pay time 9:00~21:00'), null, 2);
                }
            }
            if($fee>="10001"){
                $this->error("充值金额最大值10000元");
            }
        }
        $isorder = true;
        // 是否微信支付
        $wechat = $type == 'wechat' ? true : false;
        $valid_time = config('thirdpay.xingwu')['valid_time'];

        // 余额充值
        if ($addevent && in_array($addevent, ['wallet','miniapp']) ) {
            return $this->rechargePay($addevent);
        }
        // 获取订单
        $orderWhere = [
            'order_sn' => $order_sn,
            // 'user_id' => $this->auth->id,
            // 'xw_code'=>'',
            'status' => shoproOrder::STATUS_NOPAY
        ];
        $order = shoproOrder::where($orderWhere)->find();

        if (!$order) {
            $this->error(__('Orders not exists'), null, 2);
            // 活码链接小于30分钟
        } elseif (!empty($order['xw_pay_url']) && !$wechat && $order['xw_is_default'] != '2'&& $order['pay_type'] != 'wechat' && $order['xw_create_time'] >= time() - $valid_time) {
            $this->success('支付提交成功，请等待处理', ['url' => $order->xw_pay_url]);
            // $this->error(__('Orders not pay'),['order_sn'=>$order_sn,'id'=>$order->id,'xw_pay_url'=>$order->xw_pay_url]);
        } elseif (!empty($order['xw_pay_url']) && ($wechat || $order['xw_is_default'] == '2'|| $order['pay_type'] == 'wechat')) {
            $cloudPayInfo = json_decode($order['xw_pay_url'],true);
            if (!empty($cloudPayInfo)) {
                $this->success('支付提交成功，请等待处理', ['cloudPayInfo' => $payUrl, 'order_sn' => $order->order_sn]);
            }else{
                $this->error('亲，收款码会通过短信的方式，发送到您的手机，请您及时点击识别或扫码，进行支付', ['order_sn' => $order->order_sn]);
            }
        } elseif (!empty($order['xw_pay_url'])) {
            $this->success('支付提交成功，请等待处理', ['url' => $order->xw_pay_url]);
        }

        // 获取IP
        $ip = $this->request->ip();
        $order->ip = $ip ?? '';
        $order->save();
        $orderRes = $this->getMerchant($ip, $order['total_fee'], $wechat, $order_sn, $isDefault, $merchant, $body, $addevent);

        $order->xw_account = $merchant['business_account'];
        $order->xw_code = $merchant['code'];
        $order->province = $body['pro'];
        $order->city = $body['city'];
        if (!$orderRes || $orderRes['code'] !== 1) {
            $order->save();
            $this->error(__($orderRes['msg']), null, 2);
        }
        $payUrl = $orderRes['data']['qrCode'];
        $order->xw_orderNo = $orderRes['data']['orderNo'];
        // $order->xw_pay_url = $payUrl;
        $order->xw_pay_url = is_array($payUrl)?json_encode($payUrl):$payUrl;
        $order->xw_create_time = time();
        $order->xw_is_default = $isDefault ? '2' : '1';
        $order->pay_type = $type == 'wechat' ? 'wechat' : 'alipay';
        $order->save();
        if ($wechat || $isDefault) {
            $this->success('支付提交成功，请等待处理', ['cloudPayInfo' => $payUrl, 'order_sn' => $order->order_sn]);

            // $this->error('亲，收款码会通过短信的方式，发送到您的手机，请您及时点击识别或扫码，进行支付', ['order_sn' => $order->order_sn,'payinfo'=>$orderRes]);
        }
        $this->success('支付提交成功，请等待处理', ['url' => $payUrl, 'order_sn' => $order->order_sn]);
    }

    /**
     * @throws 去代付
     */
    public function pay_df()
    {
        $order_sn = $this->request->post("order_sn");
        $type = $this->request->post("type");
        $addevent = $this->request->post("addevent");
        $remark = $this->request->post("remark"); // 备注
        $mobile = $this->request->post("mobile"); // 手机号
        $df_user = db('user')->where('mobile',$mobile)->find();
        if((int)$mobile==(int)$this->auth->mobile){
            $this->error('代付用户不能为当前的手机号码');
        }
        // 是否微信支付
        $wechat = $type == 'wechat' ? true : false;
        // 获取订单
        $orderWhere = [
            'order_sn' => $order_sn,
            'user_id' => $this->auth->id,
            'status' => shoproOrder::STATUS_NOPAY
        ];
        $order = shoproOrder::where($orderWhere)->find();

        if (!$order) {
            $this->error(__('Orders not exists'), null, 2);
            // 活码链接小于30分钟
        }
        if (!empty($order['xw_pay_url'])) {
            $this->error('重复提交代付请求');
        }

        // 获取IP
        $ip = $this->request->ip();
        $order->ip = $ip ?? '';
        $order->save();
        $orderRes = $this->getMerchant($ip, $order['total_fee'], $wechat, $order_sn, $isDefault, $merchant, $body, $addevent);

        $order->xw_account = $merchant['business_account'];
        $order->xw_code = $merchant['code'];
        $order->province = $body['pro'];
        $order->city = $body['city'];
        if (!$orderRes || $orderRes['code'] !== 1) {
            $order->save();
            $this->error(__($orderRes['msg']), null, 2);
        }
        $payUrl = $orderRes['data']['qrCode'];
        $order->xw_orderNo = $orderRes['data']['orderNo'];
        $order->xw_pay_url = $payUrl;
        $order->xw_create_time = time();
        $order->xw_is_default = $isDefault ? '2' : '1';
        $order->pay_type = $type == 'wechat' ? 'wechat' : 'alipay';
        $order->df_remark = $remark;

        $order->df_user_id = isset($df_user['id']) ? $df_user['id'] : null;
        if ($df_user) {
            $order->is_df = 1; // 系统内用户
        } else {
            $order->is_df = 2; // 系统外用户
        }
        $order->save();
        if ($df_user) {
            $this->success('代付发送成功',['type'=>'system']);
        }
        $this->success('代付发送成功',['type'=>'qrcode']);
    }

    /**
     * 代付弹窗
     */
    public function df_info()
    {
        if (empty($this->auth->id)) {
            $this->error('请登录后操作');
        }
        $info = db('shopro_order')->where('df_user_id',$this->auth->id)->where('status',0)->where('df_reject',0)->where('is_df',1)->field('id,order_sn,goods_id,user_id,df_remark')->find();
        if ($info) {
            $info['nickname'] = db('user')->where('id',$info['user_id'])->value('nickname');
            $this->success('代付订单待支付',$info);
        }
        $this->error('没有待支付订单');
    }

    /**
     * 拒绝支付
     */
    public function reject_pay()
    {
        $order_sn = $this->request->post("order_sn");
        $up = db('shopro_order')->where('order_sn',$order_sn)->update(['df_reject'=>1]);
        if ($up) {
            $this->success('拒绝代付成功');
        }
        $this->error('拒绝代付失败');
    }

    /**
     * 代付详情信息手机号和倒计时
     */
    public function df_phone_info()
    {
        $order_sn = $this->request->post("order_sn");
        $up = db('shopro_order')->where('order_sn',$order_sn)->field('createtime,df_user_id')->find();
        if (!$up) {
            $this->error('订单不存在');
        }
        $up['mobile'] = db('user')->where('id',$up['df_user_id'])->value('mobile');
        unset($up['df_user_id']);
        $up['left_second'] = 20*60 - (time() - $up['createtime']);
        if ($up['left_second'] <= 0) {
            $up['left_second'] = 0;
        }
        unset($up['createtime']);
        $this->success('success',$up);
    }

    /**
     * 代付
     */
    public function pay_df_submit()
    {
        if (empty($this->auth->id)) {
            $this->error('请登录后操作');
        }
        $order_sn = $this->request->post("order_sn");
        $order = db('shopro_order')->where('order_sn',$order_sn)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['status'] != 0) {
            $this->error('当前状态不能代付');
        }

        $user = db('share_user')->where('user_id',$this->auth->id)->find();
        if ($user['price'] < $order['total_fee']) {
            $this->error('余额不足请充值');
        }

        $money = $user['price']-$order['total_fee'];
        $up = db('share_user')->where('user_id',$this->auth->id)->update(['price'=>$money]);
        if ($up) {
            db('shopro_order')->where('id',$order['id'])->update(['status'=>1]);
            db('user_money_log')->insert([
                'user_id'=>$this->auth->id,
                'money'=>$order['total_fee'],
                'before'=>$user['price'],
                'after'=>$user['price']-$order['total_fee'],
                'memo'=>'订单代付',
                'type'=>2,
                'createtime'=>time(),
                'order_sn'=>$order_sn,
            ]);
            $this->success('代付成功');
        }
        $this->error('代付失败');

    }

    /**
     * 代付失败原因
     */
    public function payFailReason()
    {
        $order_sn = $this->request->post("order_sn");
        $df_reject_reason = $this->request->post("df_reject_reason");
        $df_reject_remark = $this->request->post("df_reject_remark");
        $df_suggest = $this->request->post("df_suggest");

        $order = db('shopro_order')->where('order_sn',$order_sn)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        db('shopro_order')->where('id',$order['id'])->update(
            [
                'df_reject_reason'=>$df_reject_reason,
                'df_reject_remark'=>$df_reject_remark,
                'df_suggest'=>$df_suggest,
            ]
        );
        $this->success('提交成功');
    }

    /**
     * [getRandMerchant 获取城市商户]
     * @param  [type]     &$merchantData [description]
     * @param  [type]     $city          [description]
     * @param  [type]     $money         [description]
     * @return [type]                    [description]
     * @since  2022-09-27
     */
    protected function getMerchant($ip, $total_fee, $wechat, $order_sn, &$isDefault = false, &$merchant, &$body, $addevent = 'wallet')
    {
        // 太平洋电脑网接口
        $url = "http://whois.pconline.com.cn/ipJson.jsp?ip={$ip}&json=true";
        // http://whois.pconline.com.cn/ipJson.jsp?ip=120.231.20.101&json=true
        $client = new Client();
        $response = $client->get($url);
        $body = $response->getBody()->getContents();
        $encoding = mb_detect_encoding($body, ['utf-8', 'gbk', 'latin1', 'big5']);
        if ($encoding !== 'utf-8') {
            $body = mb_convert_encoding($body, 'utf-8', $encoding);
        }
        $body = json_decode(trim($body), true);
        if (empty($body['pro'])) {// 获取不到省份
            // $this->error(__('Unable to obtain IP, please contact customer service'), null, 2);
            $merchant = false;
        }else{
            // 取出与IP相关的接口
            $merchant = (new Merchant)->getProvince($body['pro'], $total_fee, $wechat);
        }


        $isDefault = false;
        // var_dump($merchant);exit;
        if (!$merchant) {//没有，取默认的
            if (!$wechat) {
                // '亲，还没有开通本地支付宝商户，请点击确定，可选择本地微信支付！';
                $msg = in_array($addevent, ['wallet', 'miniapp']) ? '亲，还没有开通支付宝商户，请点击确定，可选择微信支付！' : '亲，本地暂时还不支持支付宝支付，请用微信支付或者提货券兑换';
                $this->error(__($msg), null, 2);
            }
            $merchant = (new Merchant)->getDefaultProvince($body['pro'], $total_fee, $wechat);
            if (!$merchant && $wechat) {
                $this->error(__('Unable to obtain merchant, please contact customer service'), null, 2);
            } elseif (!$merchant) {
                // 支付宝的再找一次微信的
                $merchant = (new Merchant)->getDefaultProvince($body['pro'], $total_fee, !$wechat);
                if (!$merchant) {
                    $this->error(__('Unable to obtain merchant, please contact customer service'), null, 2);
                }
            }
            $isDefault = true;
        }
        // if ($type == 'wechat') {
        // 微信支付
        // if ($total_fee <= 1) {
        //     $total_fee = sprintf('%.2f', rand(100, 200) / 100);
        // }
        // exit;
        Merchant::where(['id' => $merchant['id']])->setInc('weight');// 添加权重

        $notify_url = in_array($addevent, ['wallet','miniapp'])?url('api/pay/notifyr', '', '', true):url('api/pay/notify', '', '', true);

        if ($addevent=='miniapp') {// 微信小程序支付
            $appid = $this->request->post("appid",'');
            $openid = $this->request->post("openid",'');

            $share_type = config('thirdpay.fenpay')['share_type'];
            if(empty($share_type)){
                $share_type = 2;
            }
            $recha = Recharge::where('order_sn',$order_sn)->find();
            if($recha){
                $recha->isNeedShare = $share_type;
                $recha->save();
            }

            $res = (new Xingwu)->mini_program_pay($merchant['token'], $total_fee, $order_sn, $notify_url,$appid,$openid, $share_type);

        }else{
            return (new Xingwu)->qrcode_pay($merchant['token'], $total_fee, $order_sn, $notify_url);
        }
        if ($res['code'] === 1) {
            $res['data']['qrCode'] = $res['data']['cloudPayInfo'];
        }
        return $res;


        // }else{
        // 支付宝支付接口
        // $orderRes = (new Xingwu)->qr_pay($merchant['code'],$order['total_fee'],$order_sn,$remark='',url('api/pay/notify','','',true));
        // ALTER TABLE `shopro_order`
        // ADD COLUMN `xw_create_time`  int NOT NULL DEFAULT 0 COMMENT '醒悟链接生成时间' AFTER `xw_pay_url`;
        // }

    }

    /**
     * [rechargePay 充值余额]
     * @return [type]     [description]
     * @since  2022-10-23
     */
    protected function rechargePay($addevent='wallet')
    {
        $type = $this->request->post("type");
        $fee = $this->request->post("fee");
        if (empty($this->auth->id)) {
            $this->error('请登录后操作', null, 2);
        }
        // $order_sn = 'pnt04nfx8sy9g2w25youzv7c55nkbv17';
        // $this->auth->id = 1;
        // 9:00~21:00
        // $today9 = strtotime(date('Y-m-d '."9:00:00"));//9点
        // $today21 = $today9 + 43200;//21点
        // if ( $today9 > time() ||  $today21 < time()) {
        //     $this->error(__('Pay time 9:00~21:00'),null,2);
        // }
        // 是否微信支付
        $wechat = $type == 'wechat' ? true : false;
        $valid_time = config('thirdpay.xingwu')['valid_time'];

        // 余额充值
        // if ($addevent && $addevent == 'wallet') {
        if ($fee < 1) {
            $this->error(__('亲，充值金额错误，请重新输入充值金额'), null, 2);
        }
        // $isorder = false;
        // }
        $recharge = (new Recharge)->addOne($type, $fee);
        // 获取IP
        $ip = $this->request->ip();
        // $ip = '175.191.124.124';
        $recharge->ip = $ip;
        $recharge->save();
        $orderRes = $this->getMerchant($ip, $fee, $wechat, $recharge->order_sn, $isDefault, $merchant, $body,$addevent);
        $recharge->xw_account = $merchant['business_account'];
        $recharge->mchId = $merchant['mchid'];
        $recharge->xw_code = $merchant['code'];
        $recharge->province = $body['pro'];
        $recharge->city = $body['city'];
        if (!$orderRes || $orderRes['code'] !== 1) {
            $recharge->save();
            $this->error(__($orderRes['msg']), null, 2);
        }
        // exit('111');
        $payUrl = $orderRes['data']['qrCode'];
        // $payUrl = $type == 'wechat' ?$orderRes['data']['qrCode']:$orderRes['data']['cloudPayInfo'];
        $recharge->xw_orderNo = $orderRes['data']['orderNo'];
        $recharge->xw_pay_url = is_array($payUrl)?json_encode($payUrl):$payUrl;
        $recharge->xw_create_time = time();
        $recharge->xw_is_default = $isDefault ? '2' : '1';
        $recharge->pay_type = $type == 'wechat' ? 'wechat' : 'alipay';
        $recharge->save();
        if ($wechat || $isDefault) {
            if($addevent == 'miniapp'){
                $this->success('支付提交成功，请等待处理', ['cloudPayInfo' => $payUrl, 'order_sn' => $recharge->order_sn]);
            }else{
                $this->error('亲，收款码会通过短信的方式，发送到您的手机，请您及时点击识别或扫码，进行支付', ['order_sn' => $recharge->order_sn]);
            }
        }
        $this->success('支付提交成功，请等待处理', ['url' => $payUrl, 'order_sn' => $recharge->order_sn]);
    }

    /**
     * [rechargeList 充值余额列表]
     * @return [type]     [description]
     * @since  2022-10-23
     */
    public function rechargeList()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $limit = $this->request->get("limit", 10);
        // 只显示充值中、和充值成功的
        // 如果订单过了5分钟，没有结果，不显示
        $list = Recharge::where(['user_id' => $this->auth->id])
            ->where(function ($query) {
                $query->where(['status' => Recharge::STATUS_PAYED])
                    ->whereOr(
                        function ($query1) {
                            $query1->where(['createtime' => ['>', time() - 300], 'status' => ['notin', [Recharge::STATUS_INVALID, Recharge::STATUS_CANCEL]]]);
                        });
            })
            ->whereBetween("createtime",[$srart,$end])
            ->field('order_sn,status,total_fee,pay_fee,pay_type,paytime,xw_orderNo,xw_pay_url')
            ->order('paytime desc')
            // ->fetchSql(true)
            // ->select();
            ->paginate($limit);
        $this->success('成功', $list);
    }

    public function paySplit()
    {
        $order_sn = $this->request->post("order_sn_split");
        $type = $this->request->post("type");
        // $order_sn = 'pnt04nfx8sy9g2w25youzv7c55nkbv17';
        // $this->auth->id = 1;
        // 9:00~21:00
        // $today9 = strtotime(date('Y-m-d '."9:00:00"));//9点
        // $today21 = $today9 + 43200;//21点
        // if ( $today9 > time() ||  $today21 < time()) {
        //     $this->error(__('Pay time 9:00~21:00'),null,2);
        // }
        // 获取订单
        $orderWhere = [
            'order_sn_s' => $order_sn,
            'user_id' => $this->auth->id,
            // 'xw_code'=>'',
            'status' => shoproOrder::STATUS_NOPAY
        ];
        $order = Split::where($orderWhere)->find();
        // 是否微信支付
        $wechat = $type == 'wechat' ? true : false;
        $valid_time = config('thirdpay.xingwu')['valid_time'];
        if (!$order) {
            $this->error(__('Orders not exists'));
            // 活码链接小于30分钟
        } elseif (!empty($order['xw_pay_url']) && !$wechat && $order['xw_is_default'] != '2' && $order['xw_create_time'] >= time() - $valid_time) {
            $this->success('支付提交成功，请等待处理', ['url' => $order->xw_pay_url]);
            // $this->error(__('Orders not pay'),['order_sn'=>$order_sn,'id'=>$order->id,'xw_pay_url'=>$order->xw_pay_url]);
        } elseif (!empty($order['xw_pay_url']) && ($wechat || $order['xw_is_default'] == '2')) {
            $this->error('亲，收款码会通过短信的方式，发送到您的手机，请您及时点击识别或扫码，进行支付');
        } elseif (!empty($order['xw_pay_url'])) {
            $this->success('支付提交成功，请等待处理', ['url' => $order->xw_pay_url]);
        }

        // 获取IP
        $ip = $this->request->ip();
        // https://zhongjunf.bigchun.com
        $order->ip = $ip ?? '';
        $order->save();
        // $ip = '175.191.124.124';
        // 太平洋电脑网接口
        $url = "http://whois.pconline.com.cn/ipJson.jsp?ip={$ip}&json=true";
        // http://whois.pconline.com.cn/ipJson.jsp?ip=120.231.20.101&json=true
        $client = new Client();
        $response = $client->get($url);
        $body = $response->getBody()->getContents();
        $encoding = mb_detect_encoding($body, ['utf-8', 'gbk', 'latin1', 'big5']);
        if ($encoding !== 'utf-8') {
            $body = mb_convert_encoding($body, 'utf-8', $encoding);
        }
        $body = json_decode(trim($body), true);
        if (empty($body['pro'])) {// 获取不到省份
            $this->error(__('Unable to obtain IP, please contact customer service'), null, 2);
        }
        // 取出与IP相关的接口

        $merchant = (new Merchant)->getProvince($body['pro'], $order['total_fee'], $wechat);

        $isDefault = false;
        // var_dump($merchant);exit;
        if (!$merchant) {//没有，取默认的
            $merchant = (new Merchant)->getDefaultProvince($body['pro'], $order['total_fee'], $wechat);
            if (!$merchant && $wechat) {
                $this->error(__('Unable to obtain merchant, please contact customer service'), null, 2);
            } elseif (!$merchant) {
                // 支付宝的再找一次微信的
                $merchant = (new Merchant)->getDefaultProvince($body['pro'], $order['total_fee'], !$wechat);
                if (!$merchant) {
                    $this->error(__('Unable to obtain merchant, please contact customer service'), null, 2);
                }
            }
            $isDefault = true;
        }
        // if ($type == 'wechat') {
        // 微信支付
        if ($order['total_fee'] <= 1) {
            $order['total_fee'] = sprintf('%.2f', rand(100, 200) / 100);
        }
        $orderRes = (new Xingwu)->qrcode_pay($merchant['token'], $order['total_fee'], $order_sn, url('api/pay/notifyr', '', '', true));
        // }else{
        // 支付宝支付接口
        // $orderRes = (new Xingwu)->qr_pay($merchant['code'],$order['total_fee'],$order_sn,$remark='',url('api/pay/notify','','',true));
        // ALTER TABLE `shopro_order`
        // ADD COLUMN `xw_create_time`  int NOT NULL DEFAULT 0 COMMENT '醒悟链接生成时间' AFTER `xw_pay_url`;
        // }
        Merchant::where(['id' => $merchant['id']])->setInc('weight');// 添加权重

        $order->xw_account = $merchant['business_account'];
        $order->xw_code = $merchant['code'];
        $order->province = $body['pro'];
        $order->city = $body['city'];
        if (!$orderRes || $orderRes['code'] !== 1) {
            $order->save();
            $this->error(__($orderRes['msg']), null, 2);
        }
        // exit('111');
        $payUrl = $orderRes['data']['qrCode'];
        // $payUrl = $type == 'wechat' ?$orderRes['data']['qrCode']:$orderRes['data']['cloudPayInfo'];
        $order->xw_orderNo = $orderRes['data']['orderNo'];
        $order->xw_pay_url = $payUrl;
        $order->xw_create_time = time();
        $order->xw_is_default = $isDefault ? '2' : '1';
        $order->pay_type = $type == 'wechat' ? 'wechat' : 'alipay';
        $order->save();
        if ($wechat || $isDefault) {
            $this->error('亲，收款码会通过短信的方式，发送到您的手机，请您及时点击识别或扫码，进行支付');
        }
        $this->success('支付提交成功，请等待处理', ['url' => $payUrl]);
        // var_dump($merchantData);exit;
    }
    /**
     * [passwd 支付密码]
     * @since  2022-11-10
     * @return [type]     [description]
     */
    public function passwd()
    {
        if (empty($this->auth->id)) {
            $this->error('请登录后操作');
        }
        $event = $this->request->post("event",'confirm');//默认确认支付密码
        $pwd = $this->request->post("pwd",'');
        $new_pwd = $this->request->post("new_pwd",'');
        $code = $this->request->post("code",'');
        $is_must = $this->request->post("is_must",'1');
        $payPasswdMod = new \app\admin\model\pay\PayPasswd;
        if ($event ==='confirm') {//确认支付密码
            $res = $payPasswdMod::confirm($this->auth->id,$pwd);
        }elseif ($event ==='set') {//set忘记密码,设置密码
            $res = $payPasswdMod::setPwd($this->auth->id,$new_pwd,$code);
        }elseif ($event ==='nopwd') {//nopwd免密
            $res = $payPasswdMod::nopwd($this->auth->id,$is_must);
        }elseif ($event ==='edit') {//edit修改支付密码
            $res = $payPasswdMod::edit($this->auth->id,$pwd,$new_pwd);
        }elseif ($event ==='info') {//edit修改支付密码
            $res = $payPasswdMod::info($this->auth->id);
        }
        // 支付密码管理 忘记支付密码、重置支付密码
        // Sms::check($mobile, $code, $event = 'paypasswdreset');
        if ($res['code'] === 1) {
            $this->success('成功');
        }
        $this->error($res['msg']);
    }
    /**
     * 订单拆分逻辑
     * @param $order
     */
    public function orderSplit()
    {
        $order_sn = $this->request->post("order_sn");
        $type = $this->request->post("type");
        if (!in_array($type, ['wechat', 'alipay'])) {
            $this->error('仅有微信，支付宝支持拆单操作');
        }
        // 获取订单
        $orderWhere = [
            'order_sn' => $order_sn,
            'user_id' => $this->auth->id,
            // 'xw_code'=>'',
            'status' => shoproOrder::STATUS_NOPAY
        ];
        $order = shoproOrder::where($orderWhere)->find();
        if (!$order) {
            $this->error('该订单不存在');
        }
        if (!empty($order['is_split'])) {
            $this->error('不能重复分单');
        }
        //金额随机拆分
        $randNum = mt_rand(20, 80);
        $splitOrderAmount1 = $order['total_fee'] * $randNum / 100;
        $splitOrderAmount2 = $order['total_fee'] - $splitOrderAmount1;
        $splitAmountArr = [
            $splitOrderAmount1, $splitOrderAmount2
        ];
        $returnArrange = [];
        foreach ($splitAmountArr as $k => $v) {
            $model = new Split();
            $model->order_id = $order['id'];
            $model->order_sn_s = $order['order_sn'] . '_' . $k;
            $model->sort = $k + 1;
            $model->user_id = $order['user_id'];
            $model->status = 0;
            $model->total_amount = $order['total_amount'];
            $model->total_fee = $splitAmountArr[$k];
            $model->pay_fee = $splitAmountArr[$k];
            $model->platform = $order['platform'];
            $returnArrange[$k] = [
                'order_sn_split' => $model->order_sn_s,
                'pay_amount' => $splitAmountArr[$k]
            ];
            if ($model->save()) {
                //写入定时队列，30分钟未支付结束订单,分单
                \think\Queue::later((3), '\addons\shopro\job\OrderAutoOper@autoCloseSplitForFd', ['order' => $order], 'shopro');
            }
        }
        $order->is_split = 1;
        $order->save();
        $this->success('分单成功', $returnArrange);
    }

    /**
     * [pay 支付]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function smspay()
    {
        $this->success('短信发送成功');
        $order_sn = $this->request->post("order_sn");
        $type = $this->request->post("type");
        // $order_sn = 'pnt04nfx8sy9g2w25youzv7c55nkbv17';
        // $this->auth->id = 1;
        // 9:00~21:00
        $today9 = strtotime(date('Y-m-d ' . "9:00:00"));//9点
        $today21 = $today9 + 43200;//21点
        // if ( $today9 > time() ||  $today21 < time()) {
        //     $this->error(__('Pay time 9:00~21:00'));
        // }
        // 获取订单
        $orderWhere = [
            'order_sn' => $order_sn,
            'user_id' => $this->auth->id,
            // 'xw_code'=>'',
            'status' => shoproOrder::STATUS_NOPAY
        ];
        $order = shoproOrder::where($orderWhere)->with('item')->find();
        $valid_time = config('thirdpay.xingwu')['valid_time'];
        if (!$order) {
            $this->error(__('Orders not exists'));
        } elseif (empty($order['xw_pay_url']) || $order['xw_create_time'] < time() - $valid_time) {
            $this->error(__('Orders pay url can not be empty'));
        }
        $url = (new \fast\Urlshorten)->createChain(config('shorturl.pay_page') . $order_sn, config('shorturl.valid_time'));
        $title = '';
        if ($url['code'] !== 1) {
            $this->error($url['msg']);
        }

        if (!empty($order->item)) {
            $title = $order->item[0]['goods_title'];
        }
        $content = sprintf(config('sms5c.content_pay'), $title, $url['result']['render_url']);
        $res = (new \sms5c\Sms)->send($this->auth->mobile, $content);
        if ($res['code'] !== 1) {
            $this->error($res['msg']);
        }
        $add = [
            'mobile' => $this->auth->mobile,
            'ip' => $this->request->ip(),
            'times' => 0,
            'createtime' => time(),
            'content' => $content,
        ];
        \think\Db::table('pay_sms')->insert($add);
        $this->success('短信发送成功');
    }

    /**
     * [pay 支付]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function payinfo()
    {
        $order_sn = $this->request->post("order_sn");
        // $order_sn = $this->request->get("order_sn");

        if (substr($order_sn, 0, 2) == 'cz') {
            // 获取充值
            $orderWhere = [
                'order_sn' => $order_sn,
                'xw_pay_url' => ['<>', ''],
                'status' => Recharge::STATUS_NOPAY
            ];
            // \addons\shopro\model\Order::detail($params)

            $field = [
                'xw_pay_url',
                'order_sn',
                'status',
                'id',
                'total_fee', //支付金额
            ];
            $order = Recharge::where($orderWhere)->field($field)->find();
        } else {
            // 获取订单
            $orderWhere = [
                'order_sn' => $order_sn,
                'xw_pay_url' => ['<>', ''],
                'status' => shoproOrder::STATUS_NOPAY
            ];
            // \addons\shopro\model\Order::detail($params)

            $field = [
                'xw_pay_url',
                'user_id',
                'order_sn',
                'status',
                'id',
                'total_amount',//订单总金额
                'total_fee', //支付金额
                'pay_fee', //实际支付金额
                'goods_original_amount', //商品原价
            ];

            $withField = [
                'id',
                'order_id',
                'goods_id',
                'goods_title',//goods_title
                'goods_image',//goods_image
                'goods_original_price',//商品原价
                'goods_price',//商品价格
                'goods_num',//购买数量
                'pay_price',//支付金额(不含运费)
            ];
            $withField = 'id,order_id,goods_id,goods_title,goods_image,goods_original_price,goods_price,goods_num,pay_price';
            $order = shoproOrder::where($orderWhere)->with(['item' => function ($query) use ($withField) {
                $query->withField($withField);
            }])->field($field)->find();
        }

        // $order = shoproOrder::where($orderWhere)->with(['item'=>$withField])->withField($withField)->field($field)->find();
        if (!$order) {
            $this->success('成功', new \stdClass);
        }
        $errorCorrectionLevel = 'H'; //容错级别
        $matrixPointSize = 5; //图片大小慢慢自己调整，只要是int就行

        require_once ROOT_PATH . 'extend/phpqrcode/phpqrcode.php';

        $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS;
        // $filePath = ROOT_PATH  . 'public' . DS . 'uploads'. DS .'tmp'. DS;
        $QR = $filePath . rand(10000, 99999) . time() . ".png";
        $object = new \phpqrcode\QRcode();
        $object->png($order->xw_pay_url, $QR, $errorCorrectionLevel, $matrixPointSize, 2);
        $order->qrcode = 'data:image/png;base64,' . base64_encode(file_get_contents($QR));
        $order->webnmae = \think\Db::name('config')->where("name", 'name')->value('value');;
        @unlink($QR);

       // $userInfo = db('user')->where('id',$order->user_id)->find();
        $auth = \app\common\library\Auth::instance();
        $auth->setAllowFields(['nickname', 'mobile', 'avatar']);
        $userInfo = $auth->getUserinfo();
        $order->nickname=$userInfo['nickname'];
        $order->mobile=$userInfo['mobile'];
        $order->avatar = $userInfo['avatar'] ? cdnurl($userInfo['avatar'], true) : '';
        $this->success('成功', $order);
    }

    /**
     * [updateTodayQuota 更新额度]
     * @return [type]     [description]
     * @since  2022-09-27
     */
    public function updateTodayQuota()
    {
        $today = date('Y-m-d');
        // 超过一小时更新缓存
        $runtime = \think\Cache::get(Merchant::CACHE_TOKEN_KEY . $this->setKey);
        if (time() - $runtime > 3600) {
            $this->login();
            \think\Cache::set(Merchant::CACHE_TOKEN_KEY . $this->setKey, time());
        }
        return;
    }

    /**
     * [updateOrder 轮询更新订单]
     * @param string $value [description]
     * @return [type]            [description]
     * @since  2022-09-27
     */
    public function updateOrder()
    {
        // 轮训规则
        // 第一分钟 10次
        // 每隔5秒一次
        //
        // 第1~5分钟 10次
        // 每隔25秒1次
        // 第5~30分钟 10次
        // 每隔2分钟一次
        // 获取订单
        $orders = shoproOrder::where('xw_orderNo', '<>', '')
            ->where('status', shoproOrder::STATUS_NOPAY)
            ->where('createtime', '>', time() - 1200)
            // ->field(['id','order_sn','user_id','pay_fee','total_fee','xw_orderNo','xw_account','ext','xw_code'])
            ->where(function ($query) {
                $query->where('xw_query_num', '=', 0);
                $time = time();
                for ($i = 1; $i < 10; $i++) {
                    $query->whereOr(function ($query1) use ($i, $time) {
                        $where = [
                            'xw_query_num' => ['=', $i],
                            'xw_create_time' => ['<=', $time - 5 * $i],
                        ];
                        $query1->where($where);
                    });
                }
                for ($i = 10; $i < 20; $i++) {
                    $query->whereOr(function ($query1) use ($i, $time) {
                        $where = [
                            'xw_query_num' => ['=', $i],
                            'xw_create_time' => ['<=', $time - 25 * $i],
                        ];
                        $query1->where($where);
                    });
                }
                for ($i = 20; $i < 30; $i++) {
                    $query->whereOr(function ($query1) use ($i, $time) {
                        $where = [
                            'xw_query_num' => ['=', $i],
                            'xw_create_time' => ['<=', $time - 180 * $i],
                        ];
                        $query1->where($where);
                    });
                }
            })
            // ->where('order_sn','=','202209512893898800009000')
            // ->where('user_id','=',1389)
            // ->where('id','>',1622)
            // ->fetchSql(true)
            ->select();
        $xingwu = (new Xingwu);
        $all = Merchant::field('id,business_account,code,token')->select();
        $merchant = [];
        foreach ($all as $key => $value) {
            $merchant[$value['code'] . $value['business_account']] = [
                'id' => $value['id'],
                'token' => $value['token'],
            ];
        }
        //支付的第三方业务码
        // $thirdCode = [
        //     'THIRD_PARTY_ERROR'=>'失败（第三方错误）',
        //     'ORDER_SUCCESS_PAY_SUCCESS'=>'下单成功并且支付成功',
        //     'ORDER_SUCCESS_PAY_INPROCESS'=>'下单成功支付处理中',
        //     'SUCCESS'=>'支付成功,停止轮询',
        //     'FAIL'=>'支付失败,停止轮询',
        //     'USERPAYING'=>'用户正在支付继续轮询',
        //     'WAIT_BUYER_PAY'=>'等待用户付款继续轮询',
        // ];
        //订单状态码
        // $statusCode = [
        //     'ORDER_UNPAID'=>'待付款',
        //     'ORDER_PAID'=>'已付款',
        //     'ORDER_REFUND'=>'已退款',
        //     'ORDER_PART_REFUND'=>'部分退款',
        //     'ORDER_HANDLE_REFUND'=>'退款处理中',
        //     'ORDER_REVOKE'=>'已撤销',
        //     'ORDER_OFF'=>'已关闭',
        // ];
        // var_dump($orders);exit;
        foreach ($orders as $key => $value) {
            $value->xw_query_num += 1;
            $value->save();
            if (empty($merchant[$value['xw_code'] . $value['xw_account']])) {
                continue;
            }
            $merchanttoken = $merchant[$value['xw_code'] . $value['xw_account']]['token'];
            $merchantid = $merchant[$value['xw_code'] . $value['xw_account']]['id'];
            $aliOrder = $xingwu->query_order($merchanttoken, $value['xw_orderNo']);
            // var_dump($aliOrder);exit;
            if ($aliOrder && $aliOrder['code'] !== 1) {
                \think\Log::record('订单请求失败：' . $value['xw_orderNo'] . var_export($aliOrder, true), 'pay_notify');
                // $aliOrder['data']['thirdCode']
                // $aliOrder['data']['statusCode']
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_UNPAID') {
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_PAID') {
                // $value->status = shoproOrder::STATUS_PAYED;
                // $value->pay_fee = $aliOrder['data']['receiptFee'];
                // $value->paytime = time();
                // 支付后流程
                Db::transaction(function () use ($value, $aliOrder, $merchantid) {
                    $notify = [
                        'transaction_id' => $aliOrder['data']['tradeNo'],
                        'buyer_email' => $value->user_id,
                        'payment_json' => json_encode($aliOrder['data']),
                        'pay_fee' => $aliOrder['data']['receiptFee'],
                        'pay_type' => $value->pay_type             // 支付方式
                    ];

                    Merchant::where('id', '=', $merchantid)->setDec('today_quota', $value['total_fee']);

                    Merchant::where(['id' => $merchantid])->setDec('weight');// 支付成功权重减少

                    $value->paymentProcess($value, $notify);
                    $temp_orders = shoproOrder::get($value->id);
                    (new CommonShare())->add_share_order($temp_orders->id, $temp_orders->goods_id, $temp_orders->user_id);
                });
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_OFF') {
                $value->status = shoproOrder::STATUS_INVALID;
                //返回额度total_fee
                // Merchant::where('id','=',$merchantid)->setInc('today_quota', $value['total_fee']);
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_REVOKE') {
                $value->status = shoproOrder::STATUS_CANCEL;
                //返回额度total_fee
                // Merchant::where('id','=',$merchantid)->setInc('today_quota', $value['total_fee']);
            }
            // $value->xw_query_num += 1;
            $value->save();
            // var_dump($orders['data']['thirdCode'],$orders['data']['statusCode'],$orders);
        }
        // var_dump($all);exit;
    }

    /**
     * [updateOrder 轮询更新充值]
     * @param string $value [description]
     * @return [type]            [description]
     * @since  2022-09-27
     */
    public function updateRecharge($where=[])
    {
        // 轮训规则
        // 第一分钟 10次
        // 每隔5秒一次
        //
        // 第1~5分钟 10次
        // 每隔25秒1次
        // 第5~30分钟 10次
        // 每隔2分钟一次
        // 获取订单
        if ($where) {
            $orders = Recharge::where('xw_orderNo', '<>', '')
                ->where('status', Recharge::STATUS_NOPAY)
                ->where($where)
                // ->fetchSql(true)
                ->select();
        }else{
            $orders = Recharge::where('xw_orderNo', '<>', '')
                ->where('status', Recharge::STATUS_NOPAY)
                ->where('createtime', '>', time() - 1200)
                // ->field(['id','order_sn','user_id','pay_fee','total_fee','xw_orderNo','xw_account','ext','xw_code'])
                ->where(function ($query) {
                    $query->where('xw_query_num', '=', 0);
                    $time = time();
                    for ($i = 1; $i < 10; $i++) {
                        $query->whereOr(function ($query1) use ($i, $time) {
                            $where = [
                                'xw_query_num' => ['=', $i],
                                'xw_create_time' => ['<=', $time - 5 * $i],
                            ];
                            $query1->where($where);
                        });
                    }
                    for ($i = 10; $i < 20; $i++) {
                        $query->whereOr(function ($query1) use ($i, $time) {
                            $where = [
                                'xw_query_num' => ['=', $i],
                                'xw_create_time' => ['<=', $time - 25 * $i],
                            ];
                            $query1->where($where);
                        });
                    }
                    for ($i = 20; $i < 30; $i++) {
                        $query->whereOr(function ($query1) use ($i, $time) {
                            $where = [
                                'xw_query_num' => ['=', $i],
                                'xw_create_time' => ['<=', $time - 180 * $i],
                            ];
                            $query1->where($where);
                        });
                    }
                })
                // ->where('order_sn','=','202209512893898800009000')
                // ->where('user_id','=',1389)
                // ->where('id','>',1622)
                // ->fetchSql(true)
                ->select();
        }

        $xingwu = (new Xingwu);
        $all = Merchant::field('id,business_account,code,token')->select();
        $merchant = [];
        foreach ($all as $key => $value) {
            $merchant[$value['code'] . $value['business_account']] = [
                'id' => $value['id'],
                'token' => $value['token'],
            ];
        }
        //支付的第三方业务码
        // $thirdCode = [
        //     'THIRD_PARTY_ERROR'=>'失败（第三方错误）',
        //     'ORDER_SUCCESS_PAY_SUCCESS'=>'下单成功并且支付成功',
        //     'ORDER_SUCCESS_PAY_INPROCESS'=>'下单成功支付处理中',
        //     'SUCCESS'=>'支付成功,停止轮询',
        //     'FAIL'=>'支付失败,停止轮询',
        //     'USERPAYING'=>'用户正在支付继续轮询',
        //     'WAIT_BUYER_PAY'=>'等待用户付款继续轮询',
        // ];
        //订单状态码
        // $statusCode = [
        //     'ORDER_UNPAID'=>'待付款',
        //     'ORDER_PAID'=>'已付款',
        //     'ORDER_REFUND'=>'已退款',
        //     'ORDER_PART_REFUND'=>'部分退款',
        //     'ORDER_HANDLE_REFUND'=>'退款处理中',
        //     'ORDER_REVOKE'=>'已撤销',
        //     'ORDER_OFF'=>'已关闭',
        // ];
        // var_dump($orders);exit;
        foreach ($orders as $key => $value) {
            echo $key . PHP_EOL;
            $value->xw_query_num += 1;
            $value->save();
            if (empty($merchant[$value['xw_code'] . $value['xw_account']])) {
                echo '未找到商户' . PHP_EOL;
                continue;
            }
            Db::startTrans();
            $recharge = Recharge::where('id', '=', $value->id)->where('status', Recharge::STATUS_NOPAY)->lock(true)->find();
            if (!$recharge) {
                Db::commit();
                continue;
            }
            $merchanttoken = $merchant[$value['xw_code'] . $value['xw_account']]['token'];
            $merchantid = $merchant[$value['xw_code'] . $value['xw_account']]['id'];
            $aliOrder = $xingwu->query_order($merchanttoken, $value['xw_orderNo']);
            // var_dump($aliOrder);exit;
            if ($aliOrder && $aliOrder['code'] !== 1) {
                \think\Log::record('订单请求失败：' . $value['xw_orderNo'] . var_export($aliOrder, true), 'pay_notify');
                // $aliOrder['data']['thirdCode']
                // $aliOrder['data']['statusCode']
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_UNPAID') {
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_PAID') {
                $recharge->status = Recharge::STATUS_PAYED;
                $recharge->pay_fee = $aliOrder['data']['receiptFee'];
               /* log_print('订单轮训start');
                log_print( $aliOrder['data']);
                log_print('订单轮训end');*/
                $recharge->chnltrxid = $aliOrder['data']['tradeNo'];
                $recharge->paytime = time();
                // 支付后流程
                Merchant::where('id', '=', $merchantid)->setDec('today_quota', $value['total_fee']);
                Merchant::where(['id' => $merchantid])->setDec('weight');// 支付成功权重减少
                (new \app\admin\model\share\ShareUser)->recharge($value, $aliOrder['data']['receiptFee']);
                // UserModel::money($aliOrder['data']['receiptFee'], $value->user_id,  'recharge', $commissionReward->id, 'money', $commissionReward,3);

                // $value->paymentProcess($value, $notify);
                // $temp_orders = shoproOrder::get($value->id);
                // (new CommonShare())->add_share_order($temp_orders->id, $temp_orders->goods_id, $temp_orders->user_id);

            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_OFF') {
                $recharge->status = Recharge::STATUS_INVALID;
                //返回额度total_fee
                // Merchant::where('id','=',$merchantid)->setInc('today_quota', $value['total_fee']);
            } elseif ($aliOrder['data']['statusCode'] == 'ORDER_REVOKE') {
                $recharge->status = Recharge::STATUS_CANCEL;
                //返回额度total_fee
                // Merchant::where('id','=',$merchantid)->setInc('today_quota', $value['total_fee']);
            }
            // $value->xw_query_num += 1;
            $recharge->save();
            Db::commit();
            // var_dump($orders['data']['thirdCode'],$orders['data']['statusCode'],$orders);
        }

        // var_dump($all);exit;
    }

    protected $setKey = 'set_timeadfasdfa';
    protected $setDayKey = 'set_dayadfasdfa';

    /**
     * [login 获取登录的token信息]
     * @param string $refreshToken [description]
     * @return [type]                   [description]
     * @since  2022-09-26
     */
    public function login($refreshToken = 'false', $province = '')
    {
        $where = ['status' => Merchant::STATUS_1];//状态为上线
        if ($province) {
            $where = [
                'province' => $province
            ];
        }
        $all = Merchant::where($where)->select();
        // $all = Merchant::where('today_quota','>',300)->where($where)->select();
        if (!$all) {
            $this->error(__('Unable to obtain merchant, please contact customer service'));
        }
        $today = date('Y-m-d');
        //是否刷新token
        // $refreshToken = $refreshToken === 'true' || ($today != \think\Cache::get(Merchant::CACHE_TOKEN_KEY.$this->setDayKey) ) ?'true':'false';
        $refreshToken = 'false';

        $xingwu = (new Xingwu);
        $provinces = [];
        foreach ($all as $value) {
            // if (!\think\Cache::get(Merchant::CACHE_TOKEN_KEY.$value->province)) {
            //     $refreshToken = 'true';
            // }
            $token = $xingwu->login($value['business_account'], $value['business_password'], $refreshToken);
            if (!$token || $token['code'] !== 1) {//登录失败
                continue;
            }
            $dbtoken = $value->token;
            $value->token = $token['data']['token'];
            // $provinces[$value->province][$value->city][] = $value->toArray();
            if ($dbtoken == $token['data']['token']) {
                continue;
            }
            $value->save();
        }
        // foreach ($provinces as $key => $value) {
        // \think\Cache::set(Merchant::CACHE_TOKEN_KEY.$key,$value);
        // }
        // \think\Cache::set(Merchant::CACHE_TOKEN_KEY.$this->setDayKey,$today);
    }

    /**
     * [notify 回调]
     * @return [type]     [description]
     * @since  2022-09-27
     */
    public function notify()
    {
        $post = $this->request->param();

        \think\Log::record(var_export($post, true), 'pay_notify');

        if (empty($post['sign'])) {
            \think\Log::record('error：' . '没有签名', 'pay_notify');
            return ('没有签名');
        }
        $one = Merchant::find();
        if (!$one) {
            \think\Log::record('error：' . '没有商户', 'pay_notify');
            return ('没有商户');

        }
        if (Xingwu::notifySign($post, $one['async_key']) != $post['sign']) {
            return ('签名不正确');

        }
        // 获取订单
        $orders = shoproOrder::where('xw_orderNo', '=', $post['orderno'])
            ->where('status', '=', shoproOrder::STATUS_NOPAY)
            ->field(['id', 'order_sn', 'pay_fee', 'user_id', 'total_fee', 'xw_orderNo', 'xw_account', 'xw_code', 'goods_id'])
            ->find();
        if (!$orders) {
            $orders = Split::where('xw_orderNo', '=', $post['orderno'])
                ->where('status', '=', shoproOrder::STATUS_NOPAY)
                ->field(['id', 'order_sn', 'pay_fee', 'user_id', 'total_fee', 'xw_orderNo', 'xw_account', 'xw_code', 'goods_id'])
                ->find();
        }
        // 处理订单
        if (!$orders) {
            \think\Log::record('error：' . '订单不存在', 'pay_notify');
            return ('订单不存在');
        }
        $merchant = Merchant::field('id,business_account,code,token')
            ->where('code', '=', $orders['xw_code'])
            ->where('business_account', '=', $orders['xw_account'])
            ->find();
        // 交易类型
        switch ($post['trxtype']) {
            case 'PUR': //消费交易
                # code...
            case 'SCP'://扫码支付
                if ($post['respcode'] == '00') {
                    // $orders->status = shoproOrder::STATUS_PAYED;
                    // $orders->pay_fee = $post['trxamt'];
                    // $orders->paytime = time();
                    // 支付后流程
                    Db::transaction(function () use ($orders, $post, $merchant) {
                        $notify = [
                            'transaction_id' => $post['trade_no'],
                            'buyer_email' => $orders->user_id,
                            'payment_json' => json_encode($post),
                            'pay_fee' => $post['trxamt'] / 100,
                            'pay_type' => 'alipay'              // 支付方式
                        ];
                        Merchant::where('id', '=', $merchant['id'])->setDec('today_quota', $orders['total_fee']);
                        Merchant::where(['id' => $merchant['id']])->setDec('weight');// 支付成功权重减少
                        $orders->paymentProcess($orders, $notify);
                        (new CommonShare())->add_share_order($orders->id, $orders->goods_id, $orders->user_id);
                    });
                    \think\Log::record('success：' . '订单不存在', 'pay_notify');
                    echo 'OK';
                } elseif ($post['respcode'] == 'P0') {
                    # code...
                } else {
                    // 没有支付，重置订单信息
                    // $orders->xw_orderNo = '';
                    // $orders->xw_account = '';
                    // $orders->xw_code = '';
                }

                break;
            case 'VID': //撤销消费
                # code...
                // break;
            case 'SPC'://扫码支付撤销
                # code...
                // break;
            case 'RVK'://撤销（消费撤销、扫码撤销、预授权撤销、预授权完成撤销）
                if ($post['respcode'] == '00') {
                    $orders->status = shoproOrder::STATUS_CANCEL;
                    // Merchant::where('id','=',$merchant['id'])->setInc('today_quota', $orders['total_fee']);
                    echo 'OK';
                }
                \think\Log::record('error：' . '订单撤销', 'pay_notify');
                break;
            case 'PRE': //预授权
                # code...
                break;
            case 'CFM': //预授权完成
                # code...
                break;
            case 'RFD': //退货
                # code...
                break;
            case 'QRY': //查询
                # code...
                break;
            case 'SPQ'://扫码支付查询
                # code...
                break;
            default:
                # code...
                break;
        }
        \think\Log::record('trxtype交易类型：' . $post['trxtype'], 'pay_notify');
        \think\Log::record('respcode交易应答码：' . $post['respcode'], 'pay_notify');
        $orders->save();

        // 交易应答码
        // $respcode = [
        //     '00'=>'交易成功',
        //     '12'=>'无效交易',
        //     '25'=>'找不到原交易或找不到交易',
        //     '30'=>'格式错误',
        //     '58'=>'不支持的交易',
        //     '63'=>'校验签名失败',
        //     '96'=>'系统异常',
        //     'P0'=>'处理中',
        // ];
        //发卡机构
        // $issuercode = [
        //     'WX'=>'微信',
        //     'ZFB01'=>'支付宝',
        //     'SFT01'=>'盛付通',
        //     'CUP'=>'银行卡',
        //     'CUP01'=>'银联扫码支付',
        //     'CUP02'=>'银联静态扫码支付',
        //     'CUP03'=>'银联动态扫码支付',
        //     'NFC'=>'碰一碰',
        // ];
        // 字段名称  字段类型 格式 备注
        // trxtype String 交易类型,详见附录A
        // trxid string 商户订单号
        // trxamt String(14) 交易金额,以分为单位
        // txndate String(14) yyyyMMddHHmmss 交易请求时间（订单创建时间）
        // paytime String(14) yyyyMMddHHmmss 交易完成时间
        // chnltrxid String 渠道流水号（微信、支付宝平台订单号；盛付通新聚合时作为分账参数使用）
        // acct String 交易账号（微信、支付宝平台userid/openid/uniqeid）
        // sub_acct String 微信子商户下的交易账号
        // fee String 手续费，以分为单位（上游暂未提供，恒为空）
        // signtype String 签名类型，恒为MD5
        // respcode String(2) 交易应答码,00交易成功;其他失败,详见附录B
        // orderno String 翼龙订单号
        // issuercode String 发卡机构，详见附录C
        // trade_no String 上游交易单号
        // sign String 签名（不参数签名计算）
    }

    /**
     * [notify 回调充值]
     * @return [type]     [description]
     * @since  2022-09-27
     */
    public function notifyr()
    {
        $post = $this->request->param();

        \think\Log::record(var_export($post, true), 'pay_notify');

        if (empty($post['sign'])) {
            \think\Log::record('error：' . '没有签名', 'pay_notify');
            return ('没有签名');
        }
        $one = Merchant::find();
        if (!$one) {
            \think\Log::record('error：' . '没有商户', 'pay_notify');
            return ('没有商户');

        }
        if (Xingwu::notifySign($post, $one['async_key']) != $post['sign']) {
            return ('签名不正确');

        }
        Db::startTrans();
        // 获取订单
        $orders = Recharge::where('xw_orderNo', '=', $post['orderno'])
            ->where('status', '=', Recharge::STATUS_NOPAY)
            ->field(['id', 'order_sn', 'pay_fee', 'user_id', 'total_fee', 'xw_orderNo', 'xw_account', 'xw_code'])
            ->lock(true)
            ->find();

        // 处理订单
        if (!$orders) {
            \think\Log::record('error：' . '订单不存在', 'pay_notify');
            Db::commit();
            return ('订单不存在');
        }
        $merchant = Merchant::field('id,business_account,code,token')
            ->where('code', '=', $orders['xw_code'])
            ->where('business_account', '=', $orders['xw_account'])
            ->find();
        // 交易类型
        switch ($post['trxtype']) {
            case 'PUR': //消费交易
                # code...
            case 'SCP'://扫码支付
                if ($post['respcode'] == '00') {
                    $orders->status = Recharge::STATUS_PAYED;
                    $orders->pay_fee = $post['trxamt'];
                    $orders->paytime = time();
                    $orders->chnltrxid = $post['chnltrxid'];
                    // 支付后流程
                    Merchant::where('id', '=', $merchant['id'])->setDec('today_quota', $orders['total_fee']);
                    Merchant::where(['id' => $merchant['id']])->setDec('weight');// 支付成功权重减少

                    (new \app\admin\model\share\ShareUser)->recharge($orders, $post['trxamt']);
                    \think\Log::record('success：' . $post['orderno'], 'pay_notify');
                    echo 'OK';
                } elseif ($post['respcode'] == 'P0') {
                    # code...
                } else {
                    // 没有支付，重置订单信息
                    // $orders->xw_orderNo = '';
                    // $orders->xw_account = '';
                    // $orders->xw_code = '';
                }

                break;
            case 'VID': //撤销消费
                # code...
                // break;
            case 'SPC'://扫码支付撤销
                # code...
                // break;
            case 'RVK'://撤销（消费撤销、扫码撤销、预授权撤销、预授权完成撤销）
                if ($post['respcode'] == '00') {
                    $orders->status = Recharge::STATUS_CANCEL;
                    // Merchant::where('id','=',$merchant['id'])->setInc('today_quota', $orders['total_fee']);
                    echo 'OK';
                }
                \think\Log::record('error：' . '订单撤销', 'pay_notify');
                break;
            case 'PRE': //预授权
                # code...
                break;
            case 'CFM': //预授权完成
                # code...
                break;
            case 'RFD': //退货
                # code...
                break;
            case 'QRY': //查询
                # code...
                break;
            case 'SPQ'://扫码支付查询
                # code...
                break;
            default:
                # code...
                break;
        }
        \think\Log::record('trxtype交易类型：' . $post['trxtype'], 'pay_notify');
        \think\Log::record('respcode交易应答码：' . $post['respcode'], 'pay_notify');
        $orders->save();
        Db::commit();

        // 交易应答码
        // $respcode = [
        //     '00'=>'交易成功',
        //     '12'=>'无效交易',
        //     '25'=>'找不到原交易或找不到交易',
        //     '30'=>'格式错误',
        //     '58'=>'不支持的交易',
        //     '63'=>'校验签名失败',
        //     '96'=>'系统异常',
        //     'P0'=>'处理中',
        // ];
        //发卡机构
        // $issuercode = [
        //     'WX'=>'微信',
        //     'ZFB01'=>'支付宝',
        //     'SFT01'=>'盛付通',
        //     'CUP'=>'银行卡',
        //     'CUP01'=>'银联扫码支付',
        //     'CUP02'=>'银联静态扫码支付',
        //     'CUP03'=>'银联动态扫码支付',
        //     'NFC'=>'碰一碰',
        // ];
        // 字段名称  字段类型 格式 备注
        // trxtype String 交易类型,详见附录A
        // trxid string 商户订单号
        // trxamt String(14) 交易金额,以分为单位
        // txndate String(14) yyyyMMddHHmmss 交易请求时间（订单创建时间）
        // paytime String(14) yyyyMMddHHmmss 交易完成时间
        // chnltrxid String 渠道流水号（微信、支付宝平台订单号；盛付通新聚合时作为分账参数使用）
        // acct String 交易账号（微信、支付宝平台userid/openid/uniqeid）
        // sub_acct String 微信子商户下的交易账号
        // fee String 手续费，以分为单位（上游暂未提供，恒为空）
        // signtype String 签名类型，恒为MD5
        // respcode String(2) 交易应答码,00交易成功;其他失败,详见附录B
        // orderno String 翼龙订单号
        // issuercode String 发卡机构，详见附录C
        // trade_no String 上游交易单号
        // sign String 签名（不参数签名计算）
    }

    /*
    * 支付结果查询接口
    */
    public function check()
    {
        $user_id = $this->auth->id;
        // 获取订单
        $orderWhere = [
            'user_id' => $user_id,
            'createtime' => [">", time() - 60]
        ];
        $order = Recharge::where($orderWhere)->field('status')->order('id', 'desc')->find();
        if (!$order) {
            $this->error('暂无充值订单');
        }
        $this->success("获取成功", ['status' => $order['status']]);
    }
}
